package com.oocl.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.oocl.pojo.User;
import com.oocl.service.UserManager;
import com.oocl.service.impl.UserManagerImpl;
import com.oocl.util.InstanceFactory;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	Logger logger = Logger.getLogger(LoginServlet.class);
	private static final long serialVersionUID = 1L;
	private UserManager manager;
    
    public LoginServlet() {
        super();
        manager = InstanceFactory.newInstance(UserManagerImpl.class);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String uname = request.getParameter("username");
		String psd = request.getParameter("password");
		
		if(null==uname || "".equals(uname.trim()) || null==psd || "".equals(psd.trim())){
			this.sendError("用户名或者密码不能为空", request, response);
			return;
		}
		User user = manager.findUserByUserName(uname);
		if(null==user){
			this.sendError("用户名不存在", request, response);
			return;
		}
		if(!user.getPassword().equals(psd)){
			this.sendError("密码错误", request, response);
			return;
		}
		
		logger.info(user.getUsername()+" user logger success");
		request.getSession().setAttribute("user", user);
		response.sendRedirect("sec/store");
	}
	
	private void sendError(String msg,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setAttribute("error", msg);
		request.getRequestDispatcher("login.jsp").forward(request, response);
	}

}
